package com.javasm.mb_store_api_final.config.adminLogin.login.phone;

import com.javasm.common.RedisKeys;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class PhoneAuthenticationProvider implements AuthenticationProvider {
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @Resource(name = "phoneLoginService1")
    UserDetailsService userDetailsService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //PhoneLoginFilter中 存入的信息
        PhoneAuthenticationToken token = (PhoneAuthenticationToken) authentication;
        String phone = (String) token.getPrincipal();//手机号
        String code = (String) token.getCredentials();//验证码
        //校验  验证码对不对
        String key = String.format(RedisKeys.UserCodePhone,phone);
        //redis中获取正确的验证码
        Object o = redisTemplate.opsForValue().get(key);
        System.out.println("111111111111111111111111111111111111111");
        System.out.println(o);
        if (o == null){
            throw new BadCredentialsException("验证码过期");
        }
        System.out.println(o);
        if (!o.equals(code)){
            throw new BadCredentialsException("验证码错误");
        }
        //代码运行到这里,说明 验证码 校验通过
        //根据 手机号,查询 用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);
        if (userDetails ==null){
            throw new BadCredentialsException("手机号不存在");
        }
        //组装成新的 PhoneAuthenticationToken
        //(用户信息,随意,权限列表)
        PhoneAuthenticationToken authenticationToken = new PhoneAuthenticationToken(userDetails,phone,userDetails.getAuthorities());
        //详情  ip等等
        authenticationToken.setDetails(token.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return PhoneAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
